package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.pojo.Question;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.*;
import com.tanhua.dubbo.server.enums.HuanXinMessageType;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.TodayBest;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TanHuaService {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private QuestionService questionService;

    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    //#默认推荐用户的ID
    @Value("tanhua.default.recommend.users")
    private String defaultRecommendUsers;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private IMService imService;

    @Reference(version = "1.0.0")
    private UserPageInfoApi userPageInfoApi;

    /**
     * 查看佳人信息
     *
     * @param userId
     * @return
     */
    public TodayBest findBestUserInfo(Long userId) {

        UserInfo userInfo = userInfoService.findUserInfo(userId);

        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }
        TodayBest todayBest = new TodayBest();
        todayBest.setId(userId);
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setAge(userInfo.getAge());
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setTags(userInfo.getTags().split(","));
        todayBest.setAvatar(userInfo.getLogo());
        //缘分值
        User user = UserThreadLocal.get();
        todayBest.setFateValue(recommendUserService.findScore(userId, user.getId()).longValue());

        //记录来访用户
        visitorsApi.saveVisitors(userId, user.getId(), "个人主页");

        return todayBest;
    }

    /**
     * 查询陌生人问题
     *
     * @param userId
     * @return
     */
    public String findStrangerQuestion(Long userId) {
        Question question = questionService.findQuestion(userId);
        if (ObjectUtil.isNotEmpty(question)) {
            return question.getTxt();
        }
        //设置一个默认的问题
        return "你的爱好是什么？";
    }

    /**
     * 回复陌生人问题
     *
     * @param userId
     * @param reply
     * @return
     */
    public Boolean answerQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        //判断该用户是否在冻结中
        Integer freezingRange = userPageInfoApi.queryUserFreezingRange(user.getId());
        if (ObjectUtil.isNotEmpty(freezingRange) && ObjectUtil.equal(freezingRange, 2)) {
            //表示用户是登录被封禁中
            return false;
        }

        UserInfo userInfo = userInfoService.findUserInfo(user.getId());
        //构建消息内容
        //{"userId":1,"huanXinId":"HX_1","nickname":"黑马小妹",
        // "strangerQuestion":"你喜欢去看蔚蓝的大海还是去爬巍峨的高山？",
        // "reply":"我喜欢秋天的落叶，夏天的泉水，冬天的雪地，只要有你一切皆可~"}
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId());
        msg.put("huanXinId", "HX_" + user.getId());
        msg.put("nickname", userInfo.getNickName());
        msg.put("strangerQuestion", findStrangerQuestion(userId));
        msg.put("reply", reply);
        //发送环信消息
        return huanXinApi.answerQuestion("HX_" + userId, HuanXinMessageType.TXT, JSONUtil.toJsonStr(msg));
    }

    /**
     * 搜索附近的人
     *
     * @param gender
     * @param distance
     * @return
     */
    public List<NearUserVo> searchNearUser(String gender, String distance) {
        User user = UserThreadLocal.get();
        //当前用户的位置信息
        UserLocationVo locationVo = userLocationApi.findLocationById(user.getId());

        if (ObjectUtil.isEmpty(locationVo)) {
            return ListUtil.empty();//hutool工具生成空集合
        }
        //通过当前用户的经纬度信息查找附近的用户
        PageInfo<UserLocationVo> locationVoPageInfo = userLocationApi.findUserByLocation(locationVo.getLongitude(),
                locationVo.getLatitude(), Convert.toDouble(distance), 1, 50);
        List<UserLocationVo> locationVoList = locationVoPageInfo.getRecords();

        if (CollUtil.isEmpty(locationVoList)) {
            return Collections.emptyList();
        }
        List<Object> userIds = CollUtil.getFieldValues(locationVoList, "userId");

        QueryWrapper<UserInfo> query = new QueryWrapper<>();
        //构造查询你条件
        query.in("user_id", userIds);
        if (StrUtil.equalsIgnoreCase(gender, "man")) {//忽略大小写
            query.eq("sex", SexEnum.MAN);
        } else if (StrUtil.equalsIgnoreCase(gender, "woman")) {
            query.eq("sex", SexEnum.WOMAN);
        }
        List<UserInfo> userInfoList = userInfoService.findPageInfo(query);

        List<NearUserVo> nearUserVoList = new ArrayList<>();
        for (UserLocationVo userLocationVo : locationVoList) {
            //查询到的附近的用户是包含用户自己的,所以要把自己做一个排除
            if (userLocationVo.getUserId().longValue() == user.getId()) {
                continue;
            }
            for (UserInfo userInfo : userInfoList) {
                if (userInfo.getUserId().longValue() == userLocationVo.getUserId().longValue()) {
                    NearUserVo nearUserVo = new NearUserVo();
                    nearUserVo.setUserId(userInfo.getUserId());
                    nearUserVo.setNickname(userInfo.getNickName());
                    nearUserVo.setAvatar(userInfo.getLogo());

                    nearUserVoList.add(nearUserVo);
                    break;
                }
            }
        }
        return nearUserVoList;
    }

    /**
     * 探花左滑右滑,查询推荐卡片列表，从推荐列表中随机选取10个用户
     *
     * @return
     */
    public List<TodayBest> lookCardList() {
        User user = UserThreadLocal.get();
        //查询到的50条数据，并不是用来直接展现，需要从这50条数据中随机返回一些数据
        List<RecommendUser> cardList = recommendUserService.findCardList(user.getId(), 50);
        if (CollUtil.isEmpty(cardList)) {
            //默认推荐列表
            List<String> recommendIds = StrUtil.split(defaultRecommendUsers, ',');
            cardList = new ArrayList<>();
            for (String recommendId : recommendIds) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Convert.toLong(recommendId));
                recommendUser.setToUserId(user.getId());

                cardList.add(recommendUser);
            }
        }
        //计算展现的数量，默认展现10个
        int min = Math.min(10, cardList.size());//返回两个int值中较小的一个。如果参数具有相同的值，则结果是相同的值。
        List<RecommendUser> list = new ArrayList<>();
        for (int i = 0; i < min; i++) {
            //TODO 可能重复
            int index = RandomUtil.randomInt(0, cardList.size());
            RecommendUser recommendUser = cardList.get(index);
            list.add(recommendUser);
        }
        List<Object> userIds = CollUtil.getFieldValues(list, "userId");
        //通过ID查找到所有的用户信息
        List<UserInfo> userInfoList = userInfoService.findUserInfoByUserIds(userIds);
        List<TodayBest> todayBestList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setFateValue(0L);
            todayBest.setAge(userInfo.getAge());
            todayBest.setTags(userInfo.getTags().split(","));
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setAvatar(userInfo.getLogo());

            todayBestList.add(todayBest);
        }
        return todayBestList;
    }

    /**
     * 探花-喜欢
     *
     * @param userId
     * @return
     */
    public boolean chooseLike(Long userId) {
        User user = UserThreadLocal.get();
        Boolean result = userLikeApi.likeUser(user.getId(), userId);
        if (!result) {
            return false;
        }
        if (userLikeApi.bothLikeOther(user.getId(), userId)) {
            imService.addFriend(userId);
        }
        return true;
    }

    /**
     * 探花-不喜欢
     *
     * @param userId
     * @return
     */
    public boolean chooseUnLike(Long userId) {
        User user = UserThreadLocal.get();
        return userLikeApi.unLikeUser(user.getId(), userId);
    }

}
